package com.safewind.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.safewind.model.Address;
import com.safewind.model.Send;
import com.safewind.model.SendQuartz;
import com.safewind.model.User;
import com.safewind.service.IAddressService;
import com.safewind.service.IHistorySendService;
import com.safewind.service.ISendQuartzService;
import com.safewind.service.ISendService;
import com.safewind.service.ISendRelateService;
import com.safewind.service.IUserService;
import com.safewind.service.IValueService;
import com.safewind.util.ConstantUtil;
import com.safewind.util.DateUtil;
import com.safewind.util.PropertiesUtil;
import com.safewind.util.StringUtil;
import com.safewind.webService.SmsService;

@Controller
@RequestMapping("/send")
public class SendController {
	@Resource
	private ISendService sendService;

	@Resource
	private ISendRelateService sendRelateService;

	@Resource
	private ISendQuartzService sendQuartzService;

	@Resource
	private IUserService userService;

	@Resource
	private IValueService valueService;

	@Resource
	private IAddressService addressService;

	@Resource
	private IHistorySendService historySendService;

	@RequestMapping("/createSend")
	@ResponseBody
	public Object createSend(HttpServletRequest request, HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		String content = request.getParameter("content");
		String sendIds = request.getParameter("sendIds");
		User user = (User) session.getAttribute("user");
		content = content.trim();
		String sign = PropertiesUtil.getValue("sign");
		content = sign + content;
		int reply = send(content, sendIds, user.getPkUserId());
		if (reply == ConstantUtil.SUCCESS) {
			map.put("success", true);
		} else {
			map.put("success", false);
			map.put("msg", StringUtil.analysisReply(reply));
		}
		return map;
	}

	@RequestMapping("/quartzSend")
	@ResponseBody
	public Object quartzSend(HttpServletRequest request, HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		String content = request.getParameter("content");
		String sendIds = request.getParameter("sendIds");
		String[] ids = sendIds.split(",");
		Integer hour = Integer.parseInt(request.getParameter("hour"));
		Integer minute = Integer.parseInt(request.getParameter("minute"));
		User user = (User) session.getAttribute("user");
		content = content.trim();
		String sign = PropertiesUtil.getValue("sign");
		content = sign + content;

		if (hour == 0 && minute == 0) {
			int reply = send(content, sendIds, user.getPkUserId());
			if (reply == ConstantUtil.SUCCESS) {
				map.put("success", true);
			} else {
				map.put("success", false);
				map.put("msg", StringUtil.analysisReply(reply));
			}
			return map;
		}
		Date date = DateUtil.add(new Date(), hour, minute);

		int sendNumber = ids.length;
		int cost = StringUtil.getCost(content, sendNumber);

		if (!userService.enoughValue(user.getPkUserId(), cost)) {
			return false;
		}

		Send send = new Send();
		send.setPkId(StringUtil.getUUID());
		send.setContent(content);
		send.setSendState(ConstantUtil.SEND_UNSENT);
		send.setUserId(user.getPkUserId());
		send.setSendTime(date);
		send.setSendNumber(sendNumber);
		send.setCost(cost);
		send.setRemark(null);

		userService.updateValue(user.getPkUserId(), -cost, "定时任务支出");

		SendQuartz sq = new SendQuartz();
		sq.setPkId(StringUtil.getUUID());
		sq.setSendId(send.getPkId());
		sq.setSendTime(send.getSendTime());
		sendQuartzService.addSendQuartz(sq);

		sendService.addSend(send);
		sendRelateService.addSendRelate(send.getPkId(), ids);
		historySendService.addQuartz(user.getPkUserId(), content, sendNumber,
				cost);
		map.put("success", true);
		return map;
	}

	private int send(String content, String sendIds, String userId) {
		String[] ids = sendIds.split(",");
		int sendNumber = ids.length;
		int reply;
		int cost = StringUtil.getCost(content, sendNumber);

		if (!userService.enoughValue(userId, cost)) {
			return ConstantUtil.NOT_ENOUGH_VALUE;
		}

		List<String> param = new ArrayList<String>();
		for (String id : ids) {
			param.add(id);
		}
		List<Address> addrList = addressService.getAddressListByIds(param);
		String phoneNumbers = "";
		for (Address addr : addrList) {
			phoneNumbers += addr.getPhoneNumber() + ",";
		}
		phoneNumbers = phoneNumbers.substring(0, phoneNumbers.length() - 1);

		try {
			reply = SmsService.sendNote(phoneNumbers, content);
			if (reply != ConstantUtil.SUCCESS) {
				return reply;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ConstantUtil.ERROR;
		}

		Send send = new Send();
		send.setPkId(StringUtil.getUUID());
		send.setContent(content);
		send.setSendState(ConstantUtil.SEND_SUCCESS);
		send.setUserId(userId);
		send.setSendTime(new Date());

		send.setSendNumber(sendNumber);
		send.setCost(cost);
		send.setRemark(null);

		userService.updateValue(userId, -cost, "发送成功");
		sendService.addSend(send);
		sendRelateService.addSendRelate(send.getPkId(), ids);
		historySendService.addSend(userId, content, sendNumber, cost);

		return reply;
	}

	@RequestMapping("/getAll")
	@ResponseBody
	public Object getAll(HttpServletRequest request, HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		User user = (User) session.getAttribute("user");
		List<Send> sendList = sendService.getAllByUserId(user.getPkUserId());
		map.put("list", sendList);
		map.put("success", true);
		return map;
	}

	@RequestMapping("/cancelQuartz")
	@ResponseBody
	public Object cancelQuartz(HttpServletRequest request, HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		String sendId = request.getParameter("sendId");
		User user = (User) session.getAttribute("user");
		Send send = sendService.getSendById(sendId);
		send.setSendState(ConstantUtil.SEND_CANCEL);
		sendService.updateSend(send);
		userService.updateValue(user.getPkUserId(), send.getCost(),
				"取消定时任务退回费用");
		historySendService.cancelQuartz(user.getPkUserId(), send.getContent());
		map.put("success", true);
		return map;
	}
}